<template>
  <div class="product-container">
    <!-- 统计信息 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-content">
            <div class="stats-icon">
              <i class="el-icon-goods"></i>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ totalProducts }}</div>
              <div class="stats-label">总商品数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-content">
            <div class="stats-icon on-sale">
              <i class="el-icon-shopping-cart-2"></i>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ onSaleProducts }}</div>
              <div class="stats-label">在售商品</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-content">
            <div class="stats-icon pending">
              <i class="el-icon-time"></i>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ pendingProducts }}</div>
              <div class="stats-label">审核中</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-content">
            <div class="stats-icon sold-out">
              <i class="el-icon-warning"></i>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ soldOutProducts }}</div>
              <div class="stats-label">售罄商品</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
        v-model="searchQuery"
        placeholder="搜索商品名称/描述"
        clearable
        @clear="handleSearch"
        @input="handleSearch"
        style="width: 300px"
      >
        <template #prefix>
          <i class="el-icon-search"></i>
        </template>
      </el-input>
      <el-select
        v-model="categoryFilter"
        placeholder="商品分类"
        clearable
        @change="handleSearch"
        style="width: 150px; margin-left: 10px"
      >
        <el-option
          v-for="item in categories"
          :key="item.categoryId"
          :label="item.name"
          :value="item.categoryId"
        />
      </el-select>
      <el-select
        v-model="statusFilter"
        placeholder="商品状态"
        clearable
        @change="handleSearch"
        style="width: 120px; margin-left: 10px"
      >
        <el-option
          v-for="item in statusOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-button
        type="primary"
        @click="handleAdd"
        style="margin-left: 10px"
        plain
      >
        添加商品
      </el-button>
      <el-button
        type="warning"
        @click="handleBatchUpdateStatus('在售')"
        :disabled="selectedProducts.length === 0"
        style="margin-left: 10px"
        plain
      >
        批量上架
      </el-button>
      <el-button
        type="info"
        @click="handleBatchUpdateStatus('已下架')"
        :disabled="selectedProducts.length === 0"
        style="margin-left: 10px"
        plain
      >
        批量下架
      </el-button>
      <el-button
        type="danger"
        @click="handleBatchDelete"
        :disabled="selectedProducts.length === 0"
        style="margin-left: 10px"
        plain
      >
        批量删除
      </el-button>
    </div>

    <!-- 商品表格 -->
    <el-table
      v-loading="loading"
      :data="paginatedProducts"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
      />
      <el-table-column
        prop="productId"
        label="ID"
        width="220"
      />
      <el-table-column
        label="商品图片"
        width="80"
      >
        <template #default="{ row }">
          <el-image
            v-if="row.imageBase64"
            :src="`data:image/jpeg;base64,${row.imageBase64}`"
            style="width: 50px; height: 50px; border-radius: 4px;"
            fit="cover"
            :preview-src-list="[`data:image/jpeg;base64,${row.imageBase64}`]"
          />
          <div
            v-else
            style="width: 50px; height: 50px; background-color: #f5f5f5; border-radius: 4px; display: flex; align-items: center; justify-content: center; color: #999; font-size: 12px;"
          >
            无图片
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="title"
        label="商品名称"
        width="200"
      />
      <el-table-column
        prop="categoryName"
        label="分类"
        width="120"
      />
      <el-table-column
        prop="price"
        label="价格"
        width="100"
      >
        <template #default="{ row }">
          ¥{{ row.price.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="status"
        label="状态"
        width="100"
      >
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="sellerNickname"
        label="卖家"
        width="120"
      />
      <el-table-column
        label="操作"
        width="240"
        fixed="right"
      >
        <template #default="{ row }">
          <div style="display: flex; flex-direction: column; align-items: center; gap: 4px;">
            <div style="display: flex; gap: 4px; justify-content: center;">
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="small"
                @click="handleEdit(row)"
                plain
              >
                编辑
              </el-button>
              <el-button
                v-if="row.status === '在售'"
                type="primary"
                size="small"
                @click="handleUpdateStatus(row, '已下架')"
                plain
              >
                下架
              </el-button>
              <el-button
                v-if="row.status === '已下架'"
                type="primary"
                size="small"
                @click="handleUpdateStatus(row, '在售')"
                plain
              >
                上架
              </el-button>
              <el-button
                v-if="row.status === '审核中'"
                type="primary"
                size="small"
                @click="handleUpdateStatus(row, '在售')"
                plain
              >
                审核通过
              </el-button>
            </div>
            <div style="display: flex; gap: 4px; justify-content: center;">
              <el-button
                v-if="row.status === '审核中'"
                type="primary"
                size="small"
                class="delete-btn"
                @click="handleUpdateStatus(row, '违规下架')"
                plain
              >
                审核拒绝
              </el-button>
              <el-button
                v-if="row.status === '在售'"
                type="primary"
                size="small"
                @click="handleUpdateStatus(row, '售罄')"
                plain
              >
                标记售罄
              </el-button>
              <el-button
                v-if="row.status === '售罄'"
                type="primary"
                size="small"
                @click="handleUpdateStatus(row, '在售')"
                plain
              >
                重新上架
              </el-button>
              <el-button
                type="primary"
                size="small"
                class="delete-btn"
                @click="handleDelete(row)"
                plain
              >
                删除
              </el-button>
            </div>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="filteredProducts.length"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 商品详情对话框 -->
    <el-dialog
      title="商品详情"
      :visible.sync="detailDialogVisible"
      width="600px"
    >
      <div v-if="currentProduct" class="product-detail">
        <div class="detail-item">
          <span class="label">商品图片：</span>
          <div class="product-image">
            <el-image
              v-if="currentProduct.imageBase64"
              :src="`data:image/jpeg;base64,${currentProduct.imageBase64}`"
              style="width: 200px; height: 200px; border-radius: 8px;"
              fit="cover"
              :preview-src-list="[`data:image/jpeg;base64,${currentProduct.imageBase64}`]"
            />
            <div
              v-else
              style="width: 200px; height: 200px; background-color: #f5f5f5; border-radius: 8px; display: flex; align-items: center; justify-content: center; color: #999; font-size: 14px;"
            >
              暂无图片
            </div>
          </div>
        </div>
        <div class="detail-item">
          <span class="label">商品ID：</span>
          <span>{{ currentProduct.productId }}</span>
        </div>
        <div class="detail-item">
          <span class="label">商品名称：</span>
          <span>{{ currentProduct.title }}</span>
        </div>
        <div class="detail-item">
          <span class="label">分类：</span>
          <span>{{ currentProduct.categoryName }}</span>
        </div>
        <div class="detail-item">
          <span class="label">价格：</span>
          <span>¥{{ currentProduct.price.toFixed(2) }}</span>
        </div>
        <div class="detail-item">
          <span class="label">状态：</span>
          <el-tag :type="getStatusType(currentProduct.status)">
            {{ getStatusText(currentProduct.status) }}
          </el-tag>
        </div>
        <div class="detail-item">
          <span class="label">卖家：</span>
          <span>{{ currentProduct.sellerNickname }}</span>
        </div>
        <div class="detail-item">
          <span class="label">描述：</span>
          <div class="description">{{ currentProduct.description }}</div>
        </div>
        <div class="detail-item">
          <span class="label">发布时间：</span>
          <span>{{ formatDate(currentProduct.createTime) }}</span>
        </div>
        <div class="detail-item">
          <span class="label">更新时间：</span>
          <span>{{ formatDate(currentProduct.updateTime) }}</span>
        </div>
      </div>
    </el-dialog>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="editDialogVisible"
      @open="onDialogOpen"
      width="500px"
      :close-on-click-modal="false"
      :z-index="3000"
      :modal-append-to-body="true"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item
          label="商品名称"
          prop="title"
        >
          <el-input
            v-model="form.title"
            placeholder="请输入商品名称"
          />
        </el-form-item>
        <el-form-item
          label="分类"
          prop="categoryId"
        >
          <el-select
            v-model="form.categoryId"
            placeholder="请选择分类"
            style="width: 100%"
          >
            <el-option
              v-for="item in categories"
              :key="item.categoryId"
              :label="item.name"
              :value="item.categoryId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input-number
            v-model="form.price"
            :precision="2"
            :step="0.01"
            controls-position="right"
            style="width: 100%;"
          ></el-input-number>
        </el-form-item>
        <el-form-item
          label="描述"
          prop="description"
        >
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="4"
            placeholder="请输入商品描述"
          />
        </el-form-item>
        <el-form-item label="商品图片" prop="imageBase64">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :on-change="handleImageChange"
            :before-upload="beforeImageUpload"
            :auto-upload="false"
          >
            <img v-if="form.imageBase64" :src="form.imageBase64" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="卖家" prop="userId">
          <el-select v-model="form.userId" placeholder="请选择卖家" filterable style="width: 100%;">
            <el-option
              v-for="user in users"
              :key="user.userId"
              :label="user.nickname"
              :value="user.userId"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleCancel" plain>取消</el-button>
        <el-button
          type="primary"
          @click="handleSubmit"
          plain
        >
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { Message, MessageBox } from 'element-ui'
import productService from '@/services/product.service'
import categoryService from '@/services/category.service'
import userService from '@/services/user.service'

export default {
  name: 'ProductManagement',
  data() {
    return {
      products: [],
      categories: [],
      users: [],
      loading: false,
      searchQuery: '',
      categoryFilter: '',
      statusFilter: '',
      detailDialogVisible: false,
      editDialogVisible: false,
      dialogTitle: '添加商品',
      currentProduct: null,
      currentId: null,
      statusOptions: [
        { value: '在售', label: '在售' },
        { value: '已下架', label: '已下架' },
        { value: '审核中', label: '审核中' },
        { value: '违规下架', label: '违规下架' },
        { value: '售罄', label: '售罄' }
      ],
      form: {
        title: '',
        categoryId: '',
        price: 0.01,
        description: '',
        imageBase64: '',
        userId: null
      },
      rules: {
        title: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '请选择商品分类', trigger: 'change' }
        ],
        price: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (value === null || value === undefined || value === '') {
                return callback(new Error('请输入商品价格'));
              }
              const numValue = Number(value);
              if (isNaN(numValue)) {
                callback(new Error('价格必须是有效的数字'));
              } else if (numValue < 0.01) {
                callback(new Error('价格不能低于 0.01'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ],
        description: [
          { required: true, message: '请输入商品描述', trigger: 'blur' },
          { min: 10, max: 500, message: '长度在 10 到 500 个字符', trigger: 'blur' }
        ],
        imageBase64: [
          { required: true, message: '请上传商品图片', trigger: 'change' }
        ],
        userId: [
          { required: true, message: '请选择卖家', trigger: 'change' }
        ]
      },
      currentPage: 1,
      pageSize: 10,
      selectedProducts: [],
      minPrice: null,
      maxPrice: null
    }
  },
  computed: {
    // 过滤商品列表
    filteredProducts() {
      let result = this.products

      // 分类过滤
      if (this.categoryFilter) {
        result = result.filter(product => product.categoryId === this.categoryFilter)
      }

      // 状态过滤
      if (this.statusFilter !== '') {
        result = result.filter(product => product.status === this.statusFilter)
      }

      // 价格过滤
      if (this.minPrice !== null && this.minPrice !== undefined && this.minPrice > 0) {
        result = result.filter(product => product.price >= this.minPrice)
      }
      if (this.maxPrice !== null && this.maxPrice !== undefined && this.maxPrice > 0) {
        result = result.filter(product => product.price <= this.maxPrice)
      }

      // 搜索过滤
      if (this.searchQuery) {
        const query = this.searchQuery.toLowerCase()
        result = result.filter(product => 
          (product.title && product.title.toLowerCase().includes(query)) ||
          (product.description && product.description.toLowerCase().includes(query))
        )
      }

      console.log('filteredProducts - 原始商品数:', this.products.length)
      console.log('filteredProducts - 过滤后商品数:', result.length)
      console.log('filteredProducts - 过滤条件:', {
        categoryFilter: this.categoryFilter,
        statusFilter: this.statusFilter,
        minPrice: this.minPrice,
        maxPrice: this.maxPrice,
        searchQuery: this.searchQuery
      })

      return result
    },

    // 分页后的商品列表
    paginatedProducts() {
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      const result = this.filteredProducts.slice(start, end)
      
      console.log('paginatedProducts - 过滤后商品数:', this.filteredProducts.length)
      console.log('paginatedProducts - 当前页:', this.currentPage)
      console.log('paginatedProducts - 每页大小:', this.pageSize)
      console.log('paginatedProducts - 分页范围:', { start, end })
      console.log('paginatedProducts - 分页后商品数:', result.length)
      
      return result
    },

    // 总商品数
    totalProducts() {
      return this.products.length
    },

    // 在售商品数
    onSaleProducts() {
      return this.products.filter(product => product.status === '在售').length
    },

    // 审核中商品数
    pendingProducts() {
      return this.products.filter(product => product.status === '审核中').length
    },

    // 售罄商品数
    soldOutProducts() {
      return this.products.filter(product => product.status === '售罄').length
    }
  },
  created() {
    this.fetchProducts()
    this.fetchCategories()
    this.fetchUsers()
  },
  methods: {
    // 获取商品列表
    async fetchProducts() {
      try {
        this.loading = true
        const response = await productService.getProducts()
        console.log('商品API响应:', response)
        
        if (response && response.code === 200) {
          // 处理Entity Framework格式的数据
          let data = response.data
          if (data && typeof data === 'object') {
            // 检查Entity Framework的$values属性
            if (data.$values && Array.isArray(data.$values)) {
              data = data.$values
              console.log('找到Entity Framework格式的商品数组数据:', data)
            } else if (Array.isArray(data)) {
              // 数据本身就是数组
              console.log('数据本身就是数组格式:', data)
            } else {
              // 尝试从其他可能的属性中获取数组
              const possibleArrayKeys = ['items', 'list', 'products', 'data', 'result']
              for (const key of possibleArrayKeys) {
                if (Array.isArray(data[key])) {
                  data = data[key]
                  console.log(`找到商品数组数据在属性 ${key}:`, data)
                  break
                }
              }
              // 如果还是找不到数组，设置为空数组
              if (!Array.isArray(data)) {
                console.warn('无法找到商品数组数据，设置为空数组')
                data = []
              }
            }
          } else {
            // 如果data不是对象，设置为空数组
            data = []
          }
          
          // 处理商品数据，确保字段映射正确
          this.products = (data || []).map(product => ({
            ...product,
            productId: product.productId || product.id || '未知商品',
            title: product.title || '未知商品',
            categoryName: product.category?.name || product.categoryName || '未知分类',
            categoryId: product.categoryId || product.category?.categoryId,
            price: product.price || 0,
            status: product.status || '在售',
            sellerNickname: product.user?.nickname || product.sellerNickname || '未知卖家',
            description: product.description || '',
            imageBase64: product.imageBase64 || product.image || '',
            createTime: product.createTime || product.createDate,
            updateTime: product.updateTime || product.updateDate
          }))
          
          console.log('商品列表:', this.products)
          console.log('商品列表长度:', this.products.length)
        } else {
          console.error('API返回错误:', response)
          this.products = []
          Message.error(response?.message || '获取商品列表失败')
        }
      } catch (error) {
        console.error('获取商品列表失败:', error)
        this.products = []
        Message.error(error?.response?.data?.message || '获取商品列表失败')
      } finally {
        this.loading = false
      }
    },

    // 获取分类列表
    async fetchCategories() {
      try {
        const response = await categoryService.getCategories()
        console.log('分类API响应:', response)
        
        if (response && response.code === 200) {
          // 处理Entity Framework格式的数据
          let data = response.data
          if (data && typeof data === 'object') {
            // 检查Entity Framework的$values属性
            if (data.$values && Array.isArray(data.$values)) {
              data = data.$values
              console.log('找到Entity Framework格式的分类数组数据:', data)
            } else if (Array.isArray(data)) {
              // 数据本身就是数组
              console.log('数据本身就是数组格式:', data)
            } else {
              // 尝试从其他可能的属性中获取数组
              const possibleArrayKeys = ['items', 'list', 'categories', 'data', 'result']
              for (const key of possibleArrayKeys) {
                if (Array.isArray(data[key])) {
                  data = data[key]
                  console.log(`找到分类数组数据在属性 ${key}:`, data)
                  break
                }
              }
              // 如果还是找不到数组，设置为空数组
              if (!Array.isArray(data)) {
                console.warn('无法找到分类数组数据，设置为空数组')
                data = []
              }
            }
          } else {
            // 如果data不是对象，设置为空数组
            data = []
          }
          
          this.categories = data || []
          console.log('分类列表:', this.categories)
          console.log('分类列表长度:', this.categories.length)
        } else {
          console.error('API返回错误:', response)
          this.categories = []
          Message.error(response?.message || '获取分类列表失败')
        }
      } catch (error) {
        console.error('获取分类列表失败:', error)
        this.categories = []
        Message.error(error?.response?.data?.message || '获取分类列表失败')
      }
    },

    // 新增：获取用户列表
    async fetchUsers() {
      try {
        const res = await userService.getUsers()
        if (res && res.code === 200) {
          let data = res.data
          if (data && typeof data === 'object') {
            if (data.$values && Array.isArray(data.$values)) {
              this.users = data.$values
            } else if (Array.isArray(data)) {
              this.users = data
            } else {
              this.users = []
            }
          } else {
            this.users = []
          }
        } else {
          this.users = []
        }
      } catch (error) {
        console.error('获取用户列表失败:', error)
        this.users = []
        Message.error('获取用户列表失败')
      }
    },

    // 搜索
    handleSearch() {
      // 重置分页到第一页
      this.currentPage = 1
      // 搜索逻辑已通过计算属性实现
    },

    // 查看商品详情
    handleView(row) {
      this.currentProduct = row
      this.detailDialogVisible = true
    },

    // 添加商品
    handleAdd() {
      this.dialogTitle = '添加商品'
      this.currentId = null
      // 清空表单
      Object.keys(this.form).forEach(key => {
        this.form[key] = ''
      })
      // 设置默认值
      this.form.price = 0.01
      this.form.userId = null
      this.editDialogVisible = true
    },

    // 编辑商品
    handleEdit(row) {
      this.dialogTitle = '编辑商品'
      this.currentId = row.productId
      // 清空表单
      Object.keys(this.form).forEach(key => {
        this.form[key] = ''
      })
      // 设置表单数据
      this.form.title = row.title || ''
      this.form.categoryId = row.categoryId || ''
      this.form.price = Number(row.price) || 0.01
      this.form.description = row.description || ''
      this.form.imageBase64 = row.imageBase64 ? (row.imageBase64.startsWith('data:') ? row.imageBase64 : 'data:image/jpeg;base64,' + row.imageBase64) : ''
      this.form.userId = row.userId || null
      this.editDialogVisible = true
    },

    onDialogOpen() {
      if (this.$refs.formRef) {
        this.$refs.formRef.clearValidate()
      }
    },

    // 更新商品状态
    async handleUpdateStatus(row, status) {
      try {
        const statusMap = {
          '在售': '上架',
          '已下架': '下架',
          '审核中': '审核',
          '违规下架': '违规下架',
          '售罄': '售罄',
          '审核通过': '审核通过',
          '审核拒绝': '审核拒绝',
          '标记售罄': '标记售罄',
          '重新上架': '重新上架'
        }
        
        const statusText = statusMap[status] || status
        await MessageBox.confirm(
          `确定要将商品状态更新为"${statusText}"吗？`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        await productService.updateProductStatus(row.productId, status)
        Message.success('状态更新成功')
        await this.fetchProducts()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('更新商品状态失败:', error)
          Message.error(error?.response?.data?.message || '更新状态失败')
        }
      }
    },

    // 删除商品
    async handleDelete(row) {
      try {
        await MessageBox.confirm('确定要删除这个商品吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        await productService.deleteProduct(row.productId)
        Message.success('删除成功')
        await this.fetchProducts()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除商品失败:', error)
          Message.error(error?.response?.data?.message || '删除失败')
        }
      }
    },

    // 提交表单
    async handleSubmit() {
      if (!this.$refs.formRef) return
      
      // 确保 form.price 是数字类型，防止潜在的类型问题导致验证失败
      this.form.price = Number(this.form.price);

      // 添加日志来检查 price 的值和类型
      console.log('提交前 form.price (已转换为Number):', this.form.price, 'Type:', typeof this.form.price);

      await this.$refs.formRef.validate(async (valid) => {
        // 在此处也打印验证结果和表单数据，以便调试
        console.log('前端表单验证结果 (valid):', valid);
        if (!valid) {
          this.$message.warning('请检查表单填写是否完整或符合规范。'); // 提示用户
          console.error('表单验证失败，请检查输入:', JSON.parse(JSON.stringify(this.form)));
          return;
        }
        
        try {
          let response
          let imageBase64ToSend = this.form.imageBase64;
          // 移除 Data URL 前缀，如果存在的话
          if (imageBase64ToSend && imageBase64ToSend.startsWith('data:')) {
            imageBase64ToSend = imageBase64ToSend.split(',')[1];
          }

          const productData = {
            title: this.form.title,
            categoryId: this.form.categoryId,
            price: this.form.price,
            description: this.form.description,
            imageBase64: imageBase64ToSend,
            userId: this.form.userId
          };

          console.log('准备发送到后端的产品数据:', JSON.parse(JSON.stringify(productData)));

          if (this.currentId) {
            // 编辑商品
            response = await productService.updateProduct(this.currentId, productData);
          } else {
            // 创建新商品
            const sellerId = this.form.userId; // 获取卖家ID
            const dataToSend = {
              title: this.form.title,
              categoryId: this.form.categoryId,
              price: this.form.price,
              description: this.form.description,
              imageBase64: imageBase64ToSend
            }; // 构建只包含ProductCreateRequest所需字段的数据
            console.log('发送给productService.createProduct的sellerId:', sellerId);
            console.log('发送给productService.createProduct的数据:', JSON.parse(JSON.stringify(dataToSend)));
            response = await productService.createProduct(sellerId, dataToSend);
          }

          if (response && response.code === 200) {
            this.$message.success(this.currentId ? '更新成功' : '添加成功');
            this.editDialogVisible = false;
            await this.fetchProducts();
          } else {
            this.$message.error(response?.message || (this.currentId ? '更新失败' : '添加失败'));
          }
        } catch (error) {
          console.error(this.currentId ? '更新商品失败:' : '添加商品失败:', error);
          this.$message.error(error?.response?.data?.message || error?.message || (this.currentId ? '更新商品失败' : '添加商品失败'));
        }
      });
    },

    // 取消
    handleCancel() {
      this.editDialogVisible = false
      // 清空表单
      Object.keys(this.form).forEach(key => {
        this.form[key] = ''
      })
      // 重置表单验证
      if (this.$refs.formRef) {
        this.$refs.formRef.clearValidate()
      }
    },

    // 获取状态类型
    getStatusType(status) {
      const types = {
        '在售': 'success',
        '已下架': 'info',
        '审核中': 'warning',
        '违规下架': 'danger',
        '售罄': 'success'
      }
      return types[status] || 'info'
    },

    // 获取状态文本
    getStatusText(status) {
      const option = this.statusOptions.find(opt => opt.value === status)
      return option ? option.label : '未知状态'
    },

    // 格式化日期
    formatDate(date) {
      if (!date) return ''
      const d = new Date(date)
      return d.toLocaleString()
    },

    // 处理分页
    handleSizeChange(newSize) {
      this.pageSize = newSize
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage
    },

    // 处理选择变化
    handleSelectionChange(selectedProducts) {
      this.selectedProducts = selectedProducts
    },

    // 批量更新状态
    async handleBatchUpdateStatus(status) {
      try {
        await MessageBox.confirm(
          `确定要将选中的商品状态更新为"${status}"吗？`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        await Promise.all(this.selectedProducts.map(product => productService.updateProductStatus(product.productId, status)))
        Message.success('批量状态更新成功')
        await this.fetchProducts()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量状态更新失败:', error)
          Message.error(error?.response?.data?.message || '批量状态更新失败')
        }
      }
    },

    // 批量删除
    async handleBatchDelete() {
      try {
        await MessageBox.confirm('确定要删除选中的商品吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        await Promise.all(this.selectedProducts.map(product => productService.deleteProduct(product.productId)))
        Message.success('批量删除成功')
        await this.fetchProducts()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量删除失败:', error)
          Message.error(error?.response?.data?.message || '批量删除失败')
        }
      }
    },

    // 处理图片上传
    handleImageChange(file) {
      const reader = new FileReader()
      reader.onload = (e) => {
        this.form.imageBase64 = e.target.result
      }
      reader.readAsDataURL(file.raw)
    },
    beforeImageUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/jpg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG && !isPNG) {
        this.$message.error('图片只能是 JPG 或 PNG 格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!')
        return false
      }
      return true
    }
  }
}
</script>

<style scoped>
.product-container {
  padding: 20px;
}

.stats-row {
  margin-bottom: 20px;
}

.stats-card {
  .stats-content {
    display: flex;
    align-items: center;
    gap: 15px;
  }

  .stats-icon {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    background-color: #409EFF;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 20px;

    &.on-sale {
      background-color: #67C23A;
    }

    &.pending {
      background-color: #E6A23C;
    }

    &.sold-out {
      background-color: #F56C6C;
    }
  }

  .stats-info {
    .stats-number {
      font-size: 24px;
      font-weight: bold;
      color: #303133;
      margin-bottom: 5px;
    }

    .stats-label {
      font-size: 14px;
      color: #909399;
    }
  }
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.delete-btn {
  color: #F56C6C;
}

.delete-btn:hover {
  color: #f78989;
}

.product-detail {
  padding: 20px;
}

.detail-item {
  margin-bottom: 15px;
  display: flex;
  align-items: flex-start;
}

.detail-item .label {
  width: 100px;
  color: #606266;
  font-weight: bold;
}

.detail-item .description {
  flex: 1;
  white-space: pre-wrap;
}

.product-image {
  width: 200px;
  height: 200px;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 15px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style> 